var member;
$(function(){
	//获取cookie中的对象
	member=getEntity("memberInfo");
	if(member){
		$("#mId").val(member.mId);
	}else{
		window.location.href=rootPath+"/";
	}
	//请求订单信息
   oneOrder();
	
	/***获取最近浏览的商品*****/
	$.ajax({
		url : rootPath+"/tracks/latelyTracks",
		type : "post",
		async : false,
		success : function(data, status) {
			var html = "";
			//移除已有的标签元素数据
			$(".recent_browse .tracks li").remove();
			//遍历结果信息
			$.each(data, function(i,result){ 
				var price=parseFloat(result.marketPrice);
				if(i<6){
					html+= "<li> "
						+" 	<a href='"+rootPath+"/goods/queryGoodsDetail?id="+result.goodsId+"' target='_blank'> "
						var img = result.picture;
						if(img==null){
							html+=" <img src='"+rootPath+"/images/more1.png' alt='' /> ";
						}else{
							html+=" <img src='"+baseFile+""+img+"' alt='' /> ";
						}
						html+=" 	<p class='des'>"+result.goodsName+"</p>"
							+" 		<p class='red'>￥"+price.toFixed(2)+"</p> "
							+" </a> "
							+" </li>";
				}
			});
			$(".recent_browse .tracks").append(html);
		},
		error : function(xhr, status, e) {
			alert("失败错误信息"+e)
		}
	});

	//取消删除订单
	$(document).on("click",".order_details .or_main .listing .multiple .cacelOrdelOrder",function(){//由于a标签是动态生成的,onclick事件传入的参数无法
		debugger;
		var $orderId = $(this).attr("orderid");
		var $status = $(this).attr("status");		
		//alert("$status: " + $status +" $orderId: "+$orderId);
		cancelOrDeleteOrder($orderId,$status);
	});
	
	//确认收货
	$(document).on("click",".order_details .or_main .listing .multiple .confirmReceiptOrder",function(){//由于a标签是动态生成的,onclick事件传入的参数无法
		var $orderId = $(this).attr("orderid");
		confirmReceiptOrder($orderId);
	});

});
//订单详细
function oneOrder(){
	var url = rootPath + "/order/oneOrder"; 
	var result = CommnUtil.ajax(url,{"orderId":orderId},"json");
	var order = null; //订单信息
	var products = null; //商品集合
	if(result.resultSuccess == true){
		order = result.data;
		if(order){
			products = order.products;
		}
		var detailUrl = rootPath + "/order/order_details?orderId="+orderId; //订单详情页
		var commentUrl = rootPath + "/order/comment?orderId="+orderId; //订单评价
		var expressUrl ='https://m.kuaidi100.com/index_all.html?type='+order.expressName+'&postid=' + order.expressCode;
		var orderCardsPayUrl = rootPath + "/order/order_card_pay?orderId="+orderId; //付款页面
//		var delOrderUrl = rootPath + "/order/cancelOrDeleteOrder?status=1&orderId="+orderId; //删除订单 status 0:取消订单 ;1：删除订单

		var status='';
		var $progress = $(".or_main .number p");
		var $info = $(".or_main .info");
        var $progressStr ="";
		//设置订单号
		$(".order_details .or_main .listing .order_number .three").text(orderId);
		var $p=$(".order_details .or_main .listing  p");
		
		//商品ul
		var $goods = $(".order_details .or_main .listing .multiple .goods");
		var $mul_ = $(".order_details .or_main .listing .multiple .mul_");
		var $height = "height:" + 116*products.length +"px";
		var payStatus = order.payStatus;
		var statusDetail='';
		var payStatus = order.payStatus;
		var shipStatus = order.shipStatus;
		var isComment = order.isComment;
		var isValid = order.isValid;
        //alert(payStatus);
		var pmtOrder =order.pmtOrder;//订单优惠
		var proType =order.proType;//优惠方式
		var pmtGoods =order.pmtGoods;
	    var proDetailMap =order.proDetailMap;//店铺促销活动
	//	alert($p.html());
	//	alert($info.html());
	//	alert($listing.html());
		var postcode = "";
		if(order.postCode){
			postcode= order.postCode;
		}else{
			postcode="";
		}
		var $infoStr='<div>详细信息</div>'
					+'<p>收货人：'+ order.memberName +'</p>'
					+'<p>收货地址：' + order.shipAddress+'</p>'
					+'<p>邮政编码：' + postcode + '</p>'
					+'<p>联系电话：'+ order.memberPhone+ '</p>';	
		$info.html($infoStr);
		/**买家备注 */
		var memo=order.memo?order.memo:'暂无备注';
		var  $pStr='<div>'
		          +'<p class="beizhu">买家备注:'+memo+'</p>'			
				   +'</div>';
		//alert($pStr);
         $(".classNote").append($pStr);

		var orderCreatTime ='';
		if(order.orderCreatTime){
			orderCreatTime = order.orderCreatTime;
		}else{
			orderCreatTime ='';
		}
		var orderPayTime='';
		if(order.orderPayTime){
			orderPayTime = order.orderPayTime;
		}else{
			orderPayTime ='';
		}
		var orderShipTime='';
		if(order.orderShipTime){
			orderShipTime = order.orderShipTime;
		}else{
			orderShipTime ='';
		}
		var orderOverTime='';
		if(order.orderOverTime){
			orderOverTime = order.orderOverTime;
		}else{
			orderOverTime ='';
		}
		var comment='<div class="r mul evaluate" style="'+ $height  +'">';
		if(order.payStatus == '3' && shipStatus =='0' && isComment=='0' && isValid=='0'){
			statusDetail ='等待买家付款';
			$progressStr ='<div><img src="'+ rootPath +'/images/tj.png" alt="提交订单" />'
						 +'<p>'
					       +'<span>'+ orderCreatTime +'</span>'
				        +'</p></div> ';
			status='<div><div class="red">'+'等待买家付款'+'</div><a href="javascript:void(0)" orderId="'+orderId+'" status="0"  class="cacelOrdelOrder"  target="_self">取消订单</a><br /><a href="'+orderCardsPayUrl+'" target="_blank" >立即付款</a></div>';
			
		}else if((payStatus == '1' || payStatus =='6')  && shipStatus =='0' && isComment=='0' && isValid=='0'){
			statusDetail ='等待卖家发货';
			$progressStr ='<div><img src="'+ rootPath +'/images/tj2.png" alt="买家付款" />'
						 +'<p>'
					       +'<span>'+ orderCreatTime +'</span>'
					       +'<span>'+orderPayTime +'</span>'
				        +'</p></div>  ';	
			status='<div><div class="red">'+'等待卖家发货'+'</div></div>';
						
		}else if((payStatus == '1' || payStatus =='6') &&( shipStatus =='1' || shipStatus == '2')&& isComment=='0' && isValid=='0'){
			statusDetail ='卖家已发货';
			$progressStr ='<div><img src="'+ rootPath +'/images/tj3.png" alt="卖家发货" />'
			 +'<p>'
		       +'<span>'+ orderCreatTime +'</span>'
		       +'<span>'+orderPayTime +'</span>'
		       +'<span>'+ orderShipTime +'</span>'
	        +'</p> </div> ';	
			status='<div><div class="red">'+'卖家已发货'+'</div><a href="'+expressUrl+'" target="_blank">查看物流</a><br /><a href="javascript:void(0)"   orderId="'+orderId+'" class="confirmReceiptOrder" target="_blank">确认收货</a></div>';
			
		}else if((payStatus == '1' || payStatus =='6') && shipStatus =='5' && isComment=='0' && isValid=='0'){
			statusDetail ='交易成功';
			$progressStr ='<div><img src="'+ rootPath +'/images/tj4.png" alt="确认收货" />'
			 +'<p>'
		       +'<span>'+ orderCreatTime +'</span>'
		       +'<span>'+orderPayTime +'</span>'
		       +'<span>'+ orderShipTime +'</span>'
		       +'<span>'+ orderOverTime +'</span>'
	        +'</p></div>';
			status='<div><div class="red">'+'交易成功'+'</div><a  orderId="'+orderId+'" status="1"  class="cacelOrdelOrder" target="_self">删除订单</a><br /><a  href="'+expressUrl+'" target="_blank">查看物流</a><br /></div>';
			//comment ='<div class="comment"><a href="'+commentUrl+'" target="_blank">立即评价</a></div>';
		}else if((payStatus == '1' || payStatus =='6') && shipStatus =='5' && isComment=='1' && isValid=='0'){
			statusDetail ='交易成功';
			$progressStr ='<div><img src="'+ rootPath +'/images/tj5.png" alt="立即评价" />'
							 +'<p>'
						       +'<span>'+ orderCreatTime +'</span>'
						       +'<span>'+orderPayTime +'</span>'
						       +'<span>'+ orderShipTime +'</span>'
						       +'<span>'+ orderOverTime +'</span>'
							   +'<span>'+ orderOverTime +'</span>'
					        +'</p></div>';
			status='<div><div class="red">'+'交易成功'+'</div><a  orderId="'+orderId+'" status="1"  class="cacelOrdelOrder" target="_self">删除订单</a><br /><a href=""><a  href="'+expressUrl+'" target="_blank">查看物流</a></div>';
			//comment ='<div class="comment"><a href="'+addCommentUrl+'" target="_blank">追加评价</a></div>';
		
		}else if(/*payStatus == '3' && shipStatus =='0' && isComment=='0' &&*/ isValid=='1'){
			statusDetail ='交易关闭';
			status='<div><div class="red">'+'交易关闭'+'</div><a href="javascript:;" orderId="'+orderId+'" status="1"  class="cacelOrdelOrder"  target="_self">删除订单</a></div>';
			
		}
		$(".or_main .number span").text("当前状态："+statusDetail);
	//	alert($progressStr);
		$progress.after($progressStr);
		
		$.each(products,function(i,product){
			  var first =  "";
			  if(i == 0){
			 	 first ="first";
			  }
			  var commentUrl = rootPath + "/order/comment?orderId="+orderId+"&productId="+product.productId; //订单评价
			  var addCommentUrl = rootPath + "/order/add_comment?orderId="+orderId+"&productId="+product.productId; //订单追加评价
			  var productDetailUrl = rootPath + "/goods/queryGoodsDetail?id=" + product.productId;
			  var goods_sku_info = '';
				if(product.goods_sku_info){
					goods_sku_info = product.goods_sku_info;
				}else{
					goods_sku_info ='无规格信息';
				}
			  var goodsSkus = goods_sku_info.split(",");
			   var skusStr = '';			   
			   $.each(goodsSkus,function(i,goodsSku){
				   if(goodsSku){
					   skusStr +=  '<span>'+ goodsSku +'</span>'  
				   }
             	});
			  
			   var $unitPrice ="";
				if(product.discountMarketPrice){
					$unitPrice = product.discountMarketPrice;
				}else{
					$unitPrice = product.marketPrice;
				}
			   //金额
				var totalPrice = parseFloat($unitPrice)*parseFloat(product.quantity);
				var goodsPro = goodsProMoney(totalPrice,product.goodsProMap);//商品促销优惠	
			//totalPrice = (totalPrice+order.shipMoney).toFixed(2);
				totalPrice = totalPrice.toFixed(2);
                var $proDetail = '无优惠';
                if(!CommnUtil.notNull(goodsPro)){
                	$proDetail = "参与了" + goodsPro.proDetailTitle+'优惠活动，优惠了'+ goodsPro.discountamount.toFixed(2) +'元';
                }
            	//判断订单详细中商品评论状态
        		if((payStatus == '1' || payStatus =='6') && shipStatus =='5' && product.isComment=='0' && isValid=='0'){
        			comment +='<div  class="'+first+'"><a href="'+commentUrl+'" target="_self">立即评价</a></div>';
        			
        		}else if((payStatus == '1' || payStatus =='6') && shipStatus =='5' && product.isComment=='1' && isValid=='0'){
        				comment +='<div class="'+first+'" >';
        				if(product.isCommentCount < 2){
        					comment +='<a href="'+addCommentUrl+'" target="_self">追加评价</a>';
        				}
        				comment +='</div>';		
        		}


        	   var picture  = rootPath+"/images/defualt.png";
        	   if(product.picture && product.picture.indexOf("goods") !=-1){
        			picture = product.picture;
        	   }
        	   var Price=parseFloat($unitPrice);
			   var $listingStr = '<ul class="clearfix">'
				                    +'<li>'
				                        +'<div class="name clearfix">'
				                             +'<a href="'+ productDetailUrl +'"><img src="' + picture + '" alt="' + product.productName + '" /></a>'
				                             +'<div class="l">'
					                               +'<a href="'+ productDetailUrl +'" target="_blank">' + product.productName + '</a>'
					                               +'<p class="f12 nine">'+skusStr+'</p>'
				                             +'</div>'
				                         +'</div>'
				                         +'<div>'
			                             //    +'<s>￥298.00</s><br />'
			                                 +'<span><i class="red">￥'+Price.toFixed(2)+'</i></span>'
		                                 +'</div>'
		                                 +'<div>'+product.quantity+'</div>'
		                                 +'<div>'+order.memberName+'</div>'
		                                 +'</li>'
				                    +'</ul>';
			    $goods.append($listingStr);
			
		});	

		comment += "</div>"
			var shipMoney=parseFloat(order.shipMoney);
	    var $mul = '<div class="l mul" style="'+$height+'">'
	    	          +'<span class="price"><i class="red">￥'+order.totalAmount+'</i></span><br />'
	    	          +'<span>(含运费：<i class="red">￥'+shipMoney.toFixed(2)+'<i>)</span>'
	    	      +'</div>'
	    	      +'<div class="l mul"  style="'+$height+'">'
	    	          +status
		          +'</div>'
    	          +comment; 
	    $mul_.append($mul);
	
		pmtGoods =(pmtGoods==null)?0:pmtGoods;
		pmtOrder =(pmtOrder==null)?0:pmtOrder;
		var shopPro  = CommnUtil.notNull(proDetailMap.proDetailTitle)?"店铺参与"+proDetailMap.proDetailTitle +"优惠活动，优惠了 <i class='red'>" + pmtOrder+"元</i>":"";
		$(".order_details .or_main .listing .note").append($pStr); 
	}else if(result.resultSuccess == false){
		alert("查询订单信息失败!")
	}
}
//商品促销优惠	
function goodsProMoney(totalPrice,goodsProMap){
	var result={};
	if(CommnUtil.notNull(goodsProMap)){
		var proType = goodsProMap.proType;
		if('0' == proType || '1' == proType ){ //订单满减或 商品满减
			result["proDetailTitle"] = goodsProMap.proDetailTitle;
			result["discountamount"] = goodsProMap.discountamount;
	    }else if('2' == proType){//商品满赠	
			result["proDetailTitle"] = goodsProMap.proDetailTitle;	
		}else if('3' == proType){//商品打折
			result["proDetailTitle"] = goodsProMap.proDetailTitle;
			 var $discountRate = goodsProMap.discountRate;
			 result["discountamount"]  = totalPrice*(1-$discountRate*1);		
		}else{
			return result;
		}
	}
	return result;
}



//刷新订单列表
function reloadOrderList(queryStatus){
	window.location.href=rootPath + '/order/orderPage?queryStatus=' + queryStatus;
}
//删除或取消
function cancelOrDeleteOrder($orderId,$status){ //订单取消订单 status 0:取消订单 ;1：删除订单
	var url =  rootPath + "/order/cancelOrDeleteOrder";
	var confirmInfo = $status == 0 ?"确认要取消订单吗？":"确认要删除订单吗？";
  var alarmInfoSuccess = $status == 0 ?"订单取消成功!":"订单删除成功!";
  var alarmInfoFail = $status == 0 ?"订单取消失败!":"订单删除失败!";
	layer.confirm(confirmInfo,{skin: 'layui-layer-red ',offset: ['40%', '40%']},function(index){

		var result = CommnUtil.ajax(url,
									{"orderId":$orderId,
								    "status":$status},
									"json");
		if(result.resultSuccess){
			 layer.msg(alarmInfoSuccess,{icon:1,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
		    	 if( $status == 0 ){
					 window.location.reload();
		    	 }else  if( $status == 1 ){
					reloadOrderList('0');//全部订单页面
		    	 }
		     }
		}else{
			 layer.msg(alarmInfoFail,{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
				 window.location.reload();
		     }
		}
	});

}

//确认收货
function  confirmReceiptOrder($orderId){
	var url =  rootPath + "/order/confirmReceiptOrder";
	layer.confirm("要确认收货吗？",{skin: 'layui-layer-red ',offset: ['40%', '40%']},function(index){

		var result = CommnUtil.ajax(url,
				{"orderId":$orderId},
				"json");
		if (result.resultSuccess) {
			layer.msg("确认收货成功", {
				icon : 1,
				skin : 'layui-layer-red ',
				offset : [ '40%', '45%' ]
			});
			Pause(this, 6000);// 调用暂停函数
			this.NextStep = function() {
			//	var commentUrl = rootPath + "/order/comment?orderId="
			//			+ $orderId; // 订单评价
			//	window.open(commentUrl, "_blank");
				 window.location.reload();
			}
		} else {
			layer.msg("确认收货失败", {
				icon : 2,
				skin : 'layui-layer-red ',
				offset : [ '40%', '45%' ]
			});
			Pause(this, 6000);//调用暂停函数
			this.NextStep = function() {
			    window.location.reload();
		    }
		}
	});
	
}